<!-- 登录页 -->
<!-- 小瓜子 更新于2020/08/23 -->

<!-- 小瓜子 更新于2020/08/25 -->
<!-- 
	1.完成注册接口对接
	2.完成验证码登录接口对接
 -->
 
<!-- 小瓜子 更新于2020/08/26 -->
<!-- 1. 添加返回新鲜事页按钮 
	 2.优化密码格式不正确提示 -->
	 
<!-- 小瓜子 更新于2020/08/27 -->
<!-- 1.更换注册时验证手机、修改密码时的url 
	 2.更换修改密码的请求方法-->

<!-- 小瓜子 更新于2020/08/27 -->
<!-- 1.添加登录页背景图-->

<!-- 小瓜子 更新于2020/09/09 -->
<!-- 彻底解决闪屏bug -->
<template>
	<view class="login">
		<view class="bgimgs" :style="'height:' + windowHeight + 'px;'">
			<image mode='aspectFill' src="../../static/login-image1.png" :class="bgiIndex == 0 ? 'active_bgimg' : ''"></image>
			<image mode='aspectFill' src="../../static/login-image2.png" :class="bgiIndex == 1 ? 'active_bgimg' : ''"></image>
			<image mode='aspectFill' src="../../static/login-image3.png" :class="bgiIndex == 2 ? 'active_bgimg' : ''"></image>
		</view>
		<view class="mask" :style="'height:' + windowHeight + 'px;'"></view>
		<!-- 2020/08/26 1.添加返回新鲜事页按钮 -->
		<view class="home_btn" @tap='home'>
			<text class="inxupt inxupttubiao20">新鲜事</text>
		</view>
		<view class="login_content">
			<!-- <view class="app_logo">
				<image src="../../static/desktop.jpg" mode="widthFix"></image>
			</view>
			<text class="title">在 西 邮</text> -->
			<!-- 密码登录 -->
			<view class="my_form" v-show="status == 0">
				<view class="input_content">
					<input type="text" class="uni-input" placeholder="手机号" placeholder-style="color: #CCC; font-size: 14px" 
						maxlength="11" @blur="finishPhoneNumber" v-model="submitForm.phoneNumber"/>
					<!-- 手机号格式错误提示 -->
					<text class="tips" v-show="tipStatus[1].isShow">{{tipStatus[1].text}}</text>
				</view>
				<view class="input_content">
					<input type="text" class="uni-input" password="true" placeholder="密码" placeholder-style="color: #CCC; font-size: 14px"
						maxlength="12" @blur="finishPassWord" v-model="submitForm.password"/>
					<!-- 密码错误提示 -->
					<text class="tips" v-show="tipStatus[2].isShow">{{tipStatus[2].text}}</text>
					<!-- 点击跳转至忘记密码 -->
					<text class="forget_pswd" @tap="forgetPassWord">忘记密码</text>
				</view>
			</view>
			<!-- 验证码登录 -->
			<view class="my_form" v-show="status == 1 || status == 2 || status == 4">
				<view class="input_content">
					<input type="text" class="uni-input" placeholder="手机号" placeholder-style="color: #CCC; font-size: 14px" 
						maxlength="11" @blur="finishPhoneNumber" v-model="submitForm.phoneNumber"/>
					<!-- 手机号格式错误提示 -->
					<text class="tips" v-show="tipStatus[1].isShow">{{tipStatus[1].text}}</text>
				</view>
				<view class="input_content">
					<input type="number" class="uni-input" placeholder="验证码" placeholder-style="color: #CCC; font-size: 14px" 
						maxlength="6" @blur="finishVerificationCode" v-model="submitForm.verificationCode"/>
					<!-- 点击获取验证码 -->
					<view type="default" class="get_vrf_code" :class="countDownShow ? 'countDownActive' : ''" @tap="getVRFCode(countDownShow)">获取验证码{{countDownShow ? ' (' + second + 's)' : ''}}</view>
					<!-- 验证码错误提示 -->
					<text class="tips" v-show="tipStatus[5].isShow">{{tipStatus[5].text}}</text>
				</view>
			</view>
			<!-- 确认密码 -->
			<view class="my_form" v-show="status == 3 || status == 5">
				<view class="input_content">
					<input type="text" class="uni-input" password="true" placeholder="输入密码" placeholder-style="color: #CCC; font-size: 14px" 
						maxlength="12" @blur="finishPassWord" v-model="submitForm.password"/>
					<!-- 密码输入提示 -->
					<text class="tips" v-show="tipStatus[0].isShow">{{tipStatus[0].text}}</text>
					<!-- 密码格式错误提示 -->
					<text class="tips" v-show="tipStatus[3].isShow">{{tipStatus[3].text}}</text>
				</view>
				<view class="input_content">
					<input type="text" class="uni-input" password="true" placeholder="确认密码" placeholder-style="color: #CCC; font-size: 14px" 
						maxlength="12" @blur="confirmPassword" v-model="cfpswd"/>
					<!-- 密码不一致提示 -->
					<text class="tips" v-show="tipStatus[4].isShow">{{tipStatus[4].text}}</text>
				</view>
			</view>
			
			<!-- 表单提交按钮 -->
			<button class="mybtn" @tap="solveTapBtn(status)">{{btnText[status]}}</button>
			
			<!-- 切换选项 切换登录方式以及注册/登录 -->
			<view class="switch_content">
				<text @tap="switchWay" class="tips" v-show="status == 0 || status == 1">{{status == 0 ? '切换验证码登录' : '切换密码登录'}}</text>
				<text @tap="switchCase" class="tips" v-show="status == 0 || status == 1 || status == 4">{{status == 4 ? '已有账号？切换登录' : '注册'}}</text>
			</view>
		</view>
	</view>
</template>

<script>
	// 判断手机号是否中国大陆合法手机号正则
	var pnmbexp = /^1(?:3\d|4[4-9]|5[0-35-9]|6[67]|7[013-8]|8\d|9\d)\d{8}$/;
	// 判断密码是否6~12位的字母和数字的组合
	var pwlengthexp = /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,12}$/;
	// 判断输入的是否自建账户
	var customUser = /^[A-z]{2,3}[0-9]+$/;
	import { _ajax } from '../../in-xupt-functions.js'
	
	export default {
		data() {
			return {
				// bgiUrls: [
				// 	'../../static/login-image1.png',
				// 	'../../static/login-image2.png',
				// 	'../../static/login-image3.png'
				// 	],
				bgiIndex: 0,
				second: 60,
				countDownShow: false,
				windowHeight: 0,
				status: 4, // 0表示密码登录状态，1表示验证码登录状态，2表示忘记密码验证手机，3表示修改密码，4表示注册状态，5表示注册时确认密码状态
				btnText: ["登录","登录","下一步","确认修改并登录","注册","注册并登录"], // 每种状态对应的按钮内容
				tipStatus: [{
					// 密码输入提示
					// 2020/08/26 修复不提示密码格式bug
					text: "输入6-12位数字与字母的组合",
					isShow: true
				},{
					// 手机号格式错误提示
					text: "*请输入正确格式账号",
					isShow: false
				},{
					// 密码错误提示
					text: "*密码错误",
					isShow: false
				},{
					// 密码格式错误提示
					text: "密码格式错误",
					isShow: false
				},{
					// 密码不一致提示
					text: "*两次输入的密码不一致",
					isShow: false
				},{
					// 验证码错误提示
					text: "*验证码格式错误",
					isShow: false
				}], 
				submitForm: {
					phoneNumber: "",
					password: "",
					verificationCode: ""
				},
				cfpswd: ""
			}
		},
		methods: {
			// 2020/08/26 1.添加返回新鲜事页按钮
			home: function () {
				uni.isRefresh = true
				uni.switchTab({
					url: '../Interest/Interest'
				})
			},
//------------------- 校验函数 ---------------------// 
			// 当完成手机号输入时，校验手机号是否正确
			finishPhoneNumber: function () {
				if (!customUser.test(this.submitForm.phoneNumber) && !pnmbexp.test(this.submitForm.phoneNumber) && this.submitForm.phoneNumber != "") {
					this.tipStatus[1].isShow = true;
					return false;
				} else {
					this.tipStatus[1].isShow = false;
					return true;
				}
			},
			// 当完成密码输入时，校验密码格式是否正确
			finishPassWord: function () {
				if (!pwlengthexp.test(this.submitForm.password) && this.submitForm.password != "") {
					// 2020/08/26 2.优化密码格式不正确提示
					uni.showToast({
						icon: 'none',
						title: this.tipStatus[3].text
					})
					this.tipStatus[0].isShow = true;
					return false;
				} else {
					this.tipStatus[0].isShow = false;
					return true;
				}
			},
			// 当完成验证码输入并点击提交时，校验验证码格式是否正确
			finishVerificationCode: function () {
				if (this.submitForm.verificationCode.length < 6 && this.submitForm.verificationCode != "") {
					this.tipStatus[5].isShow = true;
					return false;
				} else {
					this.tipStatus[5].isShow = false;
					return true;
				}
			},
			// 当再次输入密码时，校验两次密码是否输入相同
			confirmPassword: function () {
				if (this.submitForm.password != this.cfpswd && this.cfpswd != "") {
					this.tipStatus[4].isShow = true;
					return false;
				} else {
					this.tipStatus[4].isShow = false;
					return true;
				}
			},
			
//------------------- 跳转函数 ---------------------// 
			// 跳转至忘记密码的验证手机号
			forgetPassWord: function () {
				this.tipStatus.forEach(item => item.isShow = false)
				this.status = 2;
			},
			// 切换登录方式
			switchWay: function () {
				this.tipStatus.forEach(item => item.isShow = false)
				if (this.status == 0) {
					this.status = 1;
				} else {
					this.status = 0;
				}
			},
			// 切换登录或注册
			switchCase: function () {
				this.tipStatus.forEach(item => item.isShow = false)
				if (this.status == 0 || this.status == 1) {
					this.status = 4;
				} else {
					this.status = 0;
				}
			},
			
//------------------- 点击函数 ---------------------// 
			// 获取验证码
			getVRFCode: function (active) {
				// 先判断手机号是否为空
				if (!this.submitForm.phoneNumber || !this.finishPhoneNumber()) {
					// 若为空或格式错误则弹出弹框
					uni.showToast({
						title: "请输入正确手机号",
						icon: "none"
					})
				} else if (!active) {
					var _this = this
					// 倒计时
					this.countDownShow = true
					var interval = setInterval(() => {
						--this.second
						}, 1000);
					setTimeout(() => {
						clearInterval(interval)
						this.countDownShow = false
						this.second = 60;
					}, 60000);
					// 请求验证码
					_ajax({
						url: '/user/code',
						method: 'GET',
						data: {
							'phone': _this.submitForm.phoneNumber
						}
					}).then((res) => {
						// 如果返回错误，则弹窗提示错误
						if(res.data.status != 0) {
							uni.showToast({
								title: res.data.msg,
								icon: "none"
							})
						}
					})
				}else {
					return
				}
			},
			// 按钮被点击时
			solveTapBtn: function (status) {
				switch (status) {
					// 密码登录时
					case 0: {
						this.submitPassword(0);
						break;
					}
					// 验证码登录时
					case 1: {
						this.submitVerificationCode(1);
						break;
					}
					// 忘记密码验证手机时
					case 2: {
						this.submitVerificationCode(2);
						// this.tipStatus.forEach(item => item.isShow = false)
						// this.status = 3;
						break;
					}
					// 忘记密码修改密码时
					case 3: {
						this.submitPassword(3);
						break;
					}
					// 注册验证手机时
					case 4: {
						this.submitVerificationCode(4);
						// this.tipStatus.forEach(item => item.isShow = false)
						// this.status = 5;
						break;
					}
					// 注册设置密码时
					case 5: {
						this.submitPassword(5);
						break;
					}
				}
			},
			
//------------------- 提交函数 ---------------------// 
			// 提交密码和手机号
			submitPassword: function (status) {
				// 先校验手机号和密码是否为空，为空则弹出错误提示
				if (this.submitForm.phoneNumber == '') {
					uni.showToast({
						icon:'none',
						title:'请输入手机号'
					})
					return
				}
				if (this.submitForm.password == '') {
					uni.showToast({
						icon:'none',
						title:'请输入密码'
					})
					return
				}
				// 如果在确认密码界面，先验证两次密码是否一致
				if (status == 3 || status == 5) {
					if (!this.confirmPassword()) {
						this.submitForm.password = "";
						this.cfpswd = "";
						// 取消返回错误信息时弹框icon
						uni.showToast({
							icon: 'none',
							title: "两次输入的密码不一致"
						})
						return ;
					}
				}
				// 校验手机号和密码格式是否正确，都正确则发送请求
				if (this.finishPhoneNumber() && this.finishPassWord()) {
					// 使用密码登录
					if (status == 0) {
						this.loginByPassword()
					}
					// 注册时设置密码
					if (status == 5 || status == 3) {
						this.SetPassWordInRegister()
					}
				} else if (!this.finishPhoneNumber()) {
					this.submitForm.phoneNumber = ""
					uni.showToast({
						icon: "none",
						title: "手机号码格式错误"
					})
				} else if (!this.finishPassWord()) {
					this.submitForm.password = ""
					this.cfpswd = ""
					uni.showToast({
						icon: "none",
						title: "密码格式错误"
					})
				}				
			},
			// 提交验证码和手机号
			submitVerificationCode: function (status) {
				if (this.submitForm.phoneNumber == '') {
					uni.showToast({
						icon:'none',
						title:'请输入手机号'
					})
					return
				}
				if (this.submitForm.verificationCode == '') {
					uni.showToast({
						icon:'none',
						title:'请输入验证码'
					})
					return
				}
				// 校验验证码格式
				this.finishVerificationCode()
				// 验证手机号格式是否正确
				if (this.finishPhoneNumber()) {
					// 使用验证码登录
					if (status == 1) {
						this.loginByCode()
					}
					// 注册时验证手机号
					if (status == 4) {
						this.verifyPhoneInRegister()
					}
					// 忘记密码时验证手机号
					if (status == 2) {
						this.verifyPhoneInResetPassword()
					}
				}else {
					this.submitForm.phoneNumber = ""
					uni.showToast({
						icon: "none",
						title: "手机号码格式错误"
					})
				}
			},
//----------------- 登录注册函数 -------------------// 
			// 用密码登录
			loginByPassword() {
				_ajax({
					url: '/user/loginByPassword',
					method: 'POST',
					data: {
						'password': this.submitForm.password,
						'phone': this.submitForm.phoneNumber
					}
				})
				.then(res => {
					if (res.data.status == 0) {
						uni.showLoading({
							mask: true,
							title: '登录中......'
						})
						// 设置token
						this.SetTokenAndUserId({
							token: res.data.data.token,
							userId: res.data.data.userId,
							// 登录成功则跳转至新鲜事页
							resolve: () => {
								uni.isRefresh = true;
								uni.switchTab({
										url: '../Interest/Interest',
										success: () => {
											uni.hideLoading()
										}
									})
							}
						})
					} else {
						uni.showToast({
							icon: 'none',
							title: res.data.msg
						})
					}
				})
			},
			// 用验证码登录 
			loginByCode() {
				_ajax({
					url: '/user/loginByCode',
					method: 'POST',
					data: {
						'code': this.submitForm.verificationCode,
						'phone': this.submitForm.phoneNumber
					}
				})
				.then((res) => {
					uni.removeStorageSync('token')
					if(res.data.status == 0) {
						uni.showLoading({
							title: '登录中......',
							mask: true
						})
						// 设置token
						this.SetTokenAndUserId({
							token: res.data.data.token,
							userId: res.data.data.userId,
							// 登录成功则跳转至新鲜事页
							resolve: () => {
								uni.isRefresh = true;
								uni.switchTab({
										url: '../Interest/Interest',
										success: () => {
											uni.hideLoading()
										}
									})
							}
						})
					} else {
						uni.showToast({
							title: res.data.msg,
							icon: 'none'
						})
					}
				})
			},
			// 注册时验证手机
			verifyPhoneInRegister() {
				_ajax({
					url: '/user/register/validate',
					method: 'POST',
					data: {
						'code': this.submitForm.verificationCode,
						'phone': this.submitForm.phoneNumber
					}
				})
				.then((res) => {
					uni.removeStorageSync('token')
					if(res.data.status == 0) {
						this.SetTokenAndUserId({
							token: res.data.data.token,
							userId: res.data.data.userId,
							// 验证成功则跳转至设置密码
							resolve: () => {
								this.tipStatus.forEach(item => item.isShow = false)
								this.status = 5;
							}
						})
					} else {
						uni.showToast({
							title: res.data.msg,
							icon: 'none'
						})
					}
				})
			},
			// 注册时设置密码
			SetPassWordInRegister() {
				_ajax({
					url: '/user/password',
					method: 'PUT',
					data: {
						'checkPassword': this.cfpswd,
						'password': this.submitForm.password
					}
				}).then(res => {
					// 如果设置成功，跳转至新鲜事页
					if (res.data.status == 0) {
						uni.showLoading({
							mask: true,
							title: '正在跳转......'
						})
						uni.isRefresh = true;
						uni.switchTab({
							url: '../Interest/Interest',
							success: () => {
								uni.hideLoading()
							}
						})
					}else {
						// 如果设置失败则提示失败信息
						uni.showToast({
							icon: 'none',
							title: res.data.msg
						})
					}
				})
			},
			// 修改密码时验证手机
			verifyPhoneInResetPassword() {
				_ajax({
					url: '/user/password/validate',
					method: 'POST',
					data: {
						'code': this.submitForm.verificationCode,
						'phone': this.submitForm.phoneNumber
					}
				})
				.then((res) => {
					uni.removeStorageSync('token')
					console.log(res)
					if(res.data.status == 0) {
						this.SetTokenAndUserId({
							token: res.data.data.token,
							userId: res.data.data.userId,
							// 验证成功时跳转至验证密码
							resolve: () => {
								console.log('跳转')
								this.tipStatus.forEach(item => item.isShow = false)
								this.status = 3;
							}
						})
					} else {
						uni.showToast({
							title: res.data.msg,
							icon: 'none'
						})
					}
				})
			},
			// 设置storage函数
			SetTokenAndUserId(options) {
				uni.setStorage({
					key: 'token',
					data: options.token,
					success: () => {
						uni.setStorage({
							key: 'userId',
							data: options.userId,
							success: () => {
								// 设置成功之后跳转至设置密码
								options.resolve()
							}
						})
					}
				});
			}
		},
		onLoad:function(){
			uni.hideLoading()
			const query = uni.createSelectorQuery().in(this);
			const bgImgs = query.select('.bgimgs')
			setInterval(() => {
				this.bgiIndex++ ;
				if (this.bgiIndex == 3) {
					this.bgiIndex = 0;
				}
			},3000)
			uni.getSystemInfo({
				success: (data) => {
					this.windowHeight = data.windowHeight;
				}
			})
		},
		onBackPress:function(options){
			if(options.from == 'backbutton') {
				this.home()
				return true
			}
		}
	}
</script>

<style lang="less">
	.login {
		background-position: center;
		background-size: cover;
		transition: all 1s;
		.bgimgs {
			width: 100%;
			image {
				width: 100%;
				height: 100%;
				position: absolute;
				top: 0;
				transition: all 2s;
				opacity: 0;
			}
			.active_bgimg {
				opacity: 1;
			}
		}
		
		.mask {
			position: absolute;
			top: 0;
			background-color: rgba(0,0,0,.5);
			width: 100%;
		}
		.home_btn {
			position: absolute;
			top: 5%;
			left: 40rpx;
			color: #EEE;
			.inxupttubiao20::before {
				display: inline-block;
				transform: rotate(0deg);
				color: #EEE;
			}
		}
		.tips,
		.forget_pswd {
			font-size: 12px;
			color: #EEE;
			line-height: 24px;
		}
		.login_content {
			height: 40%;
			width: 60%;
			position: absolute;
			top: 35%;
			left: 20%;
			.app_logo {
				margin: 0 auto;
				width: 50px;
				height: 50px;
				image {
					width: 50px;
					height: 50px;
					border-radius: 25px;
					background-color: #FFFFFF;
				}
			}
			.title {
				display: block;
				margin: 28px auto;
				width: 100%;
				text-align: center;
				font-size: 18px;
				color: #EEE;
			}
			.my_form {
				.input_content {
					position: relative;
					margin-bottom: 40px;
					.uni-input {
						font-size: 14px;
						color: #EEE;
						border-bottom: 2px solid rgba(255,255,255, .5);
						padding: 5px 0;
					}
					.tips {
						position: absolute;
						left: 0;
					}
					.forget_pswd {
						position: absolute;
						right: 0rpx;
					}
					.get_vrf_code {
						position: absolute;
						right: 0;
						top: 0;
						font-size: 14px;
						color: #FFFFFF;
					}
					.countDownActive {
						color: #AAA;
					}
				}
				
			}
			.mybtn {
				width: 100%;
				height: 36px;
				line-height: 30px;
				font-size: 14px;
				color: #FFFFFF;
				background-color: rgba(255,255,255,.3);
				border: 2px solid rgba(255,255,255,.5);
				border-radius: 18px;
				margin-bottom: 8px;
			}
			.switch_content {
				width: 100%;
				text {
					display: block;
					text-align: center;
					margin: 0 auto;
				}
			}
		}

	}
</style>
